'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import {
  Box,
  Container,
  Typography,
  Paper,
  Button,
  Alert,
  CircularProgress,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Chip,
  IconButton,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Breadcrumbs,
  Pagination,
} from '@mui/material';
import {
  Edit as EditIcon,
  Delete as DeleteIcon,
  Visibility as VisibilityIcon,
  VisibilityOff as VisibilityOffIcon,
} from '@mui/icons-material';
import Navbar from '@/components/Navbar';
import { formatDistanceToNow } from 'date-fns';
import { zhCN } from 'date-fns/locale';

export default function ManageJobsPage() {
  const router = useRouter();
  const [jobs, setJobs] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [jobToDelete, setJobToDelete] = useState<number | null>(null);
  const [statusDialogOpen, setStatusDialogOpen] = useState(false);
  const [jobToChangeStatus, setJobToChangeStatus] = useState<any | null>(null);

  useEffect(() => {
    fetchJobs();
  }, [page]);

  const fetchJobs = async () => {
    try {
      setLoading(true);
      setError('');

      const token = localStorage.getItem('token');
      if (!token) {
        router.push('/auth/login');
        return;
      }

      // 获取用户资料
      const userResponse = await fetch('/api/profile', {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });

      if (!userResponse.ok) {
        throw new Error('获取用户资料失败');
      }

      const userData = await userResponse.json();
      
      // 检查用户是否是企业管理员
      if (!userData.is_company_admin) {
        router.push('/company/manage');
        return;
      }

      // 获取企业信息
      const companyResponse = await fetch('/api/company/info', {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });

      if (!companyResponse.ok) {
        throw new Error('获取企业信息失败');
      }

      const companyData = await companyResponse.json();
      
      // 获取该企业的招聘信息
      const jobsResponse = await fetch(`/api/recruitment/get-jobs?company_id=${companyData.id}&page=${page}&limit=10`, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });

      if (!jobsResponse.ok) {
        throw new Error('获取招聘信息失败');
      }

      const jobsData = await jobsResponse.json();
      setJobs(jobsData.jobs || []);
      setTotalPages(jobsData.pagination?.totalPages || 1);
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setLoading(false);
    }
  };

  const handlePageChange = (event: React.ChangeEvent<unknown>, value: number) => {
    setPage(value);
  };

  const handleDeleteClick = (jobId: number) => {
    setJobToDelete(jobId);
    setDeleteDialogOpen(true);
  };

  const handleStatusClick = (job: any) => {
    setJobToChangeStatus(job);
    setStatusDialogOpen(true);
  };

  const handleDeleteConfirm = async () => {
    if (!jobToDelete) return;

    try {
      setLoading(true);
      setError('');
      setSuccess('');

      const token = localStorage.getItem('token');
      if (!token) {
        router.push('/auth/login');
        return;
      }

      const response = await fetch(`/api/recruitment/delete-job/${jobToDelete}`, {
        method: 'DELETE',
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '删除招聘信息失败');
      }

      setSuccess('招聘信息已成功删除');
      setDeleteDialogOpen(false);
      
      // 重新获取招聘列表
      fetchJobs();
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setLoading(false);
    }
  };

  const handleStatusConfirm = async () => {
    if (!jobToChangeStatus) return;

    try {
      setLoading(true);
      setError('');
      setSuccess('');

      const token = localStorage.getItem('token');
      if (!token) {
        router.push('/auth/login');
        return;
      }

      const newStatus = jobToChangeStatus.status === 'active' ? 'inactive' : 'active';

      const response = await fetch(`/api/recruitment/update-job-status/${jobToChangeStatus.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ status: newStatus }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '更新招聘状态失败');
      }

      setSuccess(`招聘信息已${newStatus === 'active' ? '激活' : '下线'}`);
      setStatusDialogOpen(false);
      
      // 重新获取招聘列表
      fetchJobs();
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setLoading(false);
    }
  };

  if (loading && jobs.length === 0) {
    return (
      <>
        <Container maxWidth="lg" sx={{ py: 8, textAlign: 'center' }}>
          <CircularProgress />
          <Typography variant="h6" sx={{ mt: 2 }}>
            正在加载招聘信息...
          </Typography>
        </Container>
      </>
    );
  }

  return (
    <>
      <Box sx={{ bgcolor: 'background.default', minHeight: '100vh', py: 4 }}>
        <Container maxWidth="lg">
          <Box sx={{ mb: 4 }}>
            <Breadcrumbs aria-label="breadcrumb">
              <Link href="/" passHref>
                <Typography color="inherit">首页</Typography>
              </Link>
              <Link href="/company/manage" passHref>
                <Typography color="inherit">企业管理</Typography>
              </Link>
              <Typography color="text.primary">招聘管理</Typography>
            </Breadcrumbs>
          </Box>

          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
            <Typography variant="h4" component="h1">
              招聘管理
            </Typography>
            <Button
              variant="contained"
              color="primary"
              onClick={() => router.push('/recruitment/post')}
            >
              发布新招聘
            </Button>
          </Box>

          {error && (
            <Alert severity="error" sx={{ mb: 3 }}>
              {error}
            </Alert>
          )}

          {success && (
            <Alert severity="success" sx={{ mb: 3 }}>
              {success}
            </Alert>
          )}

          {jobs.length === 0 ? (
            <Paper sx={{ p: 4, textAlign: 'center' }}>
              <Typography variant="h6" gutterBottom>
                暂无招聘信息
              </Typography>
              <Typography variant="body1" paragraph>
                您还没有发布任何招聘信息，点击下方按钮发布第一条招聘。
              </Typography>
              <Button
                variant="contained"
                color="primary"
                onClick={() => router.push('/recruitment/post')}
              >
                发布招聘
              </Button>
            </Paper>
          ) : (
            <>
              <TableContainer component={Paper}>
                <Table>
                  <TableHead>
                    <TableRow>
                      <TableCell>职位名称</TableCell>
                      <TableCell>薪资范围</TableCell>
                      <TableCell>工作地点</TableCell>
                      <TableCell>发布时间</TableCell>
                      <TableCell>状态</TableCell>
                      <TableCell>浏览量</TableCell>
                      <TableCell>操作</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {jobs.map((job) => (
                      <TableRow key={job.id}>
                        <TableCell>
                          <Link href={`/recruitment/job/${job.id}`} passHref>
                            <Typography color="primary" sx={{ cursor: 'pointer' }}>
                              {job.title}
                            </Typography>
                          </Link>
                        </TableCell>
                        <TableCell>{job.salary_range}</TableCell>
                        <TableCell>{job.location}</TableCell>
                        <TableCell>
                          {new Date(job.created_at).toLocaleDateString('zh-CN')}
                          <Typography variant="caption" display="block" color="text.secondary">
                            {formatDistanceToNow(new Date(job.created_at), { addSuffix: true, locale: zhCN })}
                          </Typography>
                        </TableCell>
                        <TableCell>
                          <Chip
                            label={job.status === 'active' ? '已发布' : '已下线'}
                            color={job.status === 'active' ? 'success' : 'default'}
                            size="small"
                          />
                        </TableCell>
                        <TableCell>{job.views || 0}</TableCell>
                        <TableCell>
                          <IconButton
                            size="small"
                            onClick={() => router.push(`/recruitment/edit/${job.id}`)}
                            title="编辑"
                          >
                            <EditIcon fontSize="small" />
                          </IconButton>
                          <IconButton
                            size="small"
                            onClick={() => handleStatusClick(job)}
                            title={job.status === 'active' ? '下线' : '激活'}
                          >
                            {job.status === 'active' ? (
                              <VisibilityOffIcon fontSize="small" />
                            ) : (
                              <VisibilityIcon fontSize="small" />
                            )}
                          </IconButton>
                          <IconButton
                            size="small"
                            onClick={() => handleDeleteClick(job.id)}
                            title="删除"
                          >
                            <DeleteIcon fontSize="small" />
                          </IconButton>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>

              <Box sx={{ display: 'flex', justifyContent: 'center', mt: 3 }}>
                <Pagination
                  count={totalPages}
                  page={page}
                  onChange={handlePageChange}
                  color="primary"
                />
              </Box>
            </>
          )}
        </Container>
      </Box>

      {/* 删除确认对话框 */}
      <Dialog
        open={deleteDialogOpen}
        onClose={() => setDeleteDialogOpen(false)}
      >
        <DialogTitle>确认删除</DialogTitle>
        <DialogContent>
          <DialogContentText>
            您确定要删除这条招聘信息吗？此操作无法撤销。
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialogOpen(false)}>取消</Button>
          <Button onClick={handleDeleteConfirm} color="error">
            确认删除
          </Button>
        </DialogActions>
      </Dialog>

      {/* 状态更改确认对话框 */}
      <Dialog
        open={statusDialogOpen}
        onClose={() => setStatusDialogOpen(false)}
      >
        <DialogTitle>确认操作</DialogTitle>
        <DialogContent>
          <DialogContentText>
            {jobToChangeStatus?.status === 'active'
              ? '您确定要下线这条招聘信息吗？下线后求职者将无法看到此招聘。'
              : '您确定要重新发布这条招聘信息吗？发布后求职者可以看到此招聘。'}
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setStatusDialogOpen(false)}>取消</Button>
          <Button onClick={handleStatusConfirm} color="primary">
            确认
          </Button>
        </DialogActions>
      </Dialog>
    </>
  );
}
